package com.billManage.common.utils.baidu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import okhttp3.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public  class  BaiDuOrcUtil {
    public static final String API_KEY = "kfSFQSZMfjUI5NRRlG2oYVD9";
    public static final String SECRET_KEY = "EZV14VivXqonkvdPf91VCzDB8Uo6G8e3";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static  Map<String, String>  vatInvoice(String base64) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice";
        try {
            // 本地文件路径
            String imgParam = URLEncoder.encode(base64, "UTF-8");
            String param = "image=" + imgParam;
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAccessToken();
            String result = HttpUtil.post(url, accessToken, param);
            return invoiceData(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    static Map<String, String> invoiceData(String result) throws Exception {
        Map<String, String> invoiceData = new HashMap<>();
        JSONObject words_result = JSONObject.parseObject(result).getJSONObject("words_result");
        if(words_result.isEmpty()){
              throw new Exception();
        }
        invoiceData.put("invoiceNum",words_result.getString("InvoiceNum")) ;
        invoiceData.put("totalAmount",words_result.getString("TotalAmount")) ;
        invoiceData.put("invoiceDate",words_result.getString("InvoiceDate")) ;
        invoiceData.put("purchaserName",words_result.getString("PurchaserName")) ;
        invoiceData.put("sellerName",words_result.getString("SellerName")) ;
        JSONArray  CommodityUnit = words_result.getJSONArray("CommodityUnit");
        if(!CommodityUnit.isEmpty() && CommodityUnit.size() >= 0){
            JSONObject JSONObject = CommodityUnit.getJSONObject(0);
            invoiceData.put("unit",JSONObject.getString("word")) ;
        }

        JSONArray  CommodityType = words_result.getJSONArray("CommodityType");
        if(!CommodityType.isEmpty() && CommodityType.size() >= 0){
            JSONObject JSONObject = CommodityType.getJSONObject(0);
            invoiceData.put("type",JSONObject.getString("word")) ;
        }
        JSONArray  CommodityNum = words_result.getJSONArray("CommodityNum");
        if(!CommodityNum.isEmpty() && CommodityNum.size() >= 0){
            JSONObject JSONObject = CommodityNum.getJSONObject(0);
            invoiceData.put("num",JSONObject.getString("word")) ;
        }
        JSONArray  CommodityPrice = words_result.getJSONArray("CommodityPrice");
        if(!CommodityPrice.isEmpty() && CommodityPrice.size() >= 0){
            JSONObject JSONObject = CommodityPrice.getJSONObject(0);
            invoiceData.put("price",JSONObject.getString("word")) ;
        }
        JSONArray  CommodityAmount = words_result.getJSONArray("CommodityAmount");
        if(!CommodityAmount.isEmpty() && CommodityAmount.size() >= 0){
            JSONObject JSONObject = CommodityAmount.getJSONObject(0);
            invoiceData.put("amount",JSONObject.getString("word")) ;
        }
        JSONArray  CommodityTaxRate = words_result.getJSONArray("CommodityTaxRate");
        if(!CommodityTaxRate.isEmpty() && CommodityTaxRate.size() >= 0){
            JSONObject JSONObject = CommodityTaxRate.getJSONObject(0);
            invoiceData.put("taxRate",JSONObject.getString("word")) ;
        }
        JSONArray  CommodityTax = words_result.getJSONArray("CommodityTax");
        if(!CommodityTax.isEmpty() && CommodityTax.size() >= 0){
            JSONObject JSONObject = CommodityTax.getJSONObject(0);
            invoiceData.put("tax",JSONObject.getString("word")) ;
        }
        return invoiceData;
    }

    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    public static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    public static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return  JSONObject.parseObject(response.body().string()).getString("access_token");
    }
}
